<form lay-filter="proTaskForm" class="layui-form open-form" id="benchmarkBookForm">
  <div class="open-model" id="benchmarkBookFormModel">
    <div class="open-auto">
      <input type="hidden" name="code" />
      <input type="hidden" name="resTaskId" />
      <input type="hidden" name="skuCode" />
      <input type="hidden" name="skuName" />
      <input type="hidden" name="skuSpec" />
      <input type="hidden" name="productDetailId" />
      <input type="hidden" name="source" />
      <input type="hidden" name="productType" />
      <input type="hidden" name="productTypeName" />
      <input type="hidden" name="materialNature" />
      <input type="hidden" name="materialNatureName" />
      <input type="hidden" name="productAttr" />
      <!-- //产品属性 -->
      <input type="hidden" name="productAttrName" />
      <!-- //产品属性名称 -->
      <input type="hidden" name="remark" />
      <input type="hidden" name="drawName" />
      <input type="hidden" name="drawUrl" />
      <input type="hidden" name="isRelevance" />
      <input type="hidden" name="drawMoldName" />
      <input type="hidden" name="drawMoldUrl" />
      <table lay-filter="benchmarkBookFormTable" id="benchmarkBookFormTable"></table>
      <div class="layui-tab" lay-filter="test-handle" lay-allowclose="true">
        <ul class="layui-tab-title">
          <li class="layui-this" lay-id="YSBZ">产品验收标准</li>
          <li lay-id="BOMGUIHUA">MRP物料BOM规划</li>
          <li lay-id="GCGUIHUA">工艺规划</li>
          <li lay-id="ZHILIANG">质量管理</li>
          <li lay-id="WULIAO">物料管理</li>
          <li lay-id="GONGZI">工序工资</li>
        </ul>
        <div class="layui-tab-content">
          <div class="layui-tab-item layui-show">
            <div class="layui-form-item layui-row">
              <div class="layui-col-md6">
                <label class="layui-form-label w-auto">版本编号：</label>
                <div class="layui-input-inline">
                  <input style="border: none" type="text" value="BCZ380C9.2.1.4.1.1.1-2" disabled id="infoVersion" name="infoVersion" class="layui-input" />
                </div>
              </div>
            </div>
            <div class="layui-form-item layui-row" style="display: flex">
              <div class="layui-col-md6" style="flex: 2; margin-right: 20px">
                <div style="cursor: default; margin-bottom: 15px">
                  图纸预览：
                  <button class="layui-btn" id="drawImageBtn" type="button">上传图纸</button>
                  <button class="layui-btn" id="checkImageBtn" type="button">选择图纸</button>
                </div>
                <!-- <div
                  id="drawImage"
                  style="
                    width: 100%;
                    height: 100%;
                    display: flex;
                    justify-content: center;
                  "
                ></div> -->
                <table class="layui-table" id="drawImageTable" lay-filter="drawImageTable"></table>
              </div>
              <div class="layui-col-md6" style="flex: 3">
                <div style="cursor: default; display: flex; justify-content: space-between; align-items: center">
                  <div>质检标准</div>
                  <div>
                    <button class="layui-btn" id="addTestItem" type="button">添加质检标准</button>
                  </div>
                </div>
                <table class="layui-table" id="testItemTable" lay-filter="testItemTable"></table>
              </div>
            </div>
          </div>
          <div class="layui-tab-item" id="bom_info">
            <div class="layui-form-item layui-row">
              <div class="layui-form-item layui-row">
                <table class="layui-table" id="bomTreeTable" lay-filter="bomTreeTable"></table>
              </div>
            </div>
          </div>
          <div class="layui-tab-item" id="gy">
            <div class="layui-form-item layui-row">
              <div class="layui-form-item layui-row">
                <div class="layui-col-md4">
                  <label class="layui-form-label">选择工艺路线：</label>
                  <div class="layui-input-block">
                    <select id="templateId" lay-search="" name="templateId" lay-filter="templateId" class="common-select-search"></select>
                  </div>
                </div>
              </div>
              <div class="layui-form-item layui-row">
                <div class="layui-col-md12">
                  <div style="padding: 0 10px; display: flex; justify-content: space-between; align-items: center">
                    <h2>工序管理</h2>
                    <div>
                      <button type="button" id="checkProcess" class="layui-btn">选择工序</button>
                      <button type="button" id="moldUploadInfoBtn" class="layui-btn">添加工序</button>
                    </div>
                  </div>
                  <table class="layui-table" id="productProjectTable" lay-filter="productProjectTable"></table>
                </div>
                <!-- <div class="layui-col-md3" style="padding: 0 15px">
                  <form lay-filter="processForm" id="processForm" class="layui-form">
                    <div style="margin-bottom: 10px; margin-left: 5px">
                      <h2>工艺参数</h2>
                    </div>
                    <div id="processFormContent">
                      <div class="layui-form-item">
                        <label class="layui-form-label">工序内容</label>
                        <div class="layui-input-block">
                          <textarea name="content" placeholder="请输入工艺参数" class="layui-input" />
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <label class="layui-form-label">夹具</label>
                        <div class="layui-input-block">
                          <input type="text" name="fixture" placeholder="请输入夹具" class="layui-input" />
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <label class="layui-form-label">量具</label>
                        <div class="layui-input-block">
                          <input type="text" name="measuringTools" placeholder="请输入量具" class="layui-input" />
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <label class="layui-form-label">报工单位</label>
                        <div class="layui-input-block">
                          <input type="text" name="unitId" placeholder="请输入报工单位" class="layui-input" />
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <label class="layui-form-label">工时定额(分钟)</label>
                        <div class="layui-input-block">
                          <input type="text" name="hoursQuota" placeholder="请输入工时定额" class="layui-input" />
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <label class="layui-form-label">工资定额(元)</label>
                        <div class="layui-input-block">
                          <input type="text" name="salaryQuota" placeholder="请输入工资定额" class="layui-input" />
                        </div>
                      </div>
                      <div class="layui-form-item">
                        <label class="layui-form-label">NG工资定额</label>
                        <div class="layui-input-block">
                          <input type="text" name="ngSalaryQuota" placeholder="请输入NG工资定额" class="layui-input" />
                        </div>
                      </div>

                      <div class="layui-form-item">
                        <label class="layui-form-label">质检类型</label>
                        <div class="layui-input-block">
                          <select id="qualityType" name="qualityType" v-on="$listeners" lay-filter="qualityType" class="common-select-search">
                            <option value="0" selected>不需要质检</option>
                            <option value="1">抽检</option>
                            <option value="2">全检</option>
                          </select>
                        </div>
                      </div>
                    </div>
                  </form>
                </div> -->
                <!-- <div class="layui-col-md5">
                  <div style="padding: 0 10px; display: flex; justify-content: space-between; align-items: center">
                    <h2>关联物料</h2>
                    <button type="button" id="addLastSku" class="layui-btn">选择上个工序产成品</button>
                    <button type="button" id="addSku" class="layui-btn">添加物料</button>
                  </div>
                  <table class="layui-table" id="skuTable" lay-filter="skuTable"></table>
                </div> -->
              </div>
            </div>
            <!-- <div>
              <button class="layui-btn" id="moldUploadInfoBtn">添加工序</button>
            </div> -->
            <!-- <div class="modelImgDiv">
              <div class="layui-form-item layui-row">
                <table class="layui-table" id="productProjectTable" lay-filter="productProjectTable"></table>
              </div>
              <div class="layui-form-item layui-row"></div>
            </div> -->
          </div>
          <div class="layui-tab-item" id="ZHILIANG">
            <div class="layui-col-md4" style="padding-right: 2%">
              <table class="layui-table" id="zhiliangTable" lay-filter="zhiliangTable"></table>
            </div>
            <div class="layui-col-md8">
              <div style="display: flex; justify-content: flex-end">
                <button type="button" id="addZhijian" class="layui-btn" style="display: none">添加质检项目</button>
              </div>
              <table class="layui-table" id="zhijianTable" lay-filter="zhijianTable"></table>
            </div>
          </div>
          <div class="layui-tab-item" id="WULIAO">
            <div class="layui-col-md4" style="margin-right: 5%">
              <table class="layui-table" id="wuliaoTable" lay-filter="wuliaoTable"></table>
            </div>
            <div class="layui-col-md7">
              <div style="display: flex; justify-content: flex-end">
                <!-- <button type="button" id="addLastSku" class="layui-btn">选择上个工序产成品</button> -->
                <button type="button" id="addSkuByBom" class="layui-btn">从BOM中添加物料</button>

                <button type="button" id="addSku" class="layui-btn">添加物料</button>
              </div>
              <table class="layui-table" id="skuTable" lay-filter="skuTable"></table>
            </div>
          </div>
          <div class="layui-tab-item" id="GONGZI">
            <table class="layui-table" id="gongziTable" lay-filter="gongziTable"></table>
          </div>
        </div>
      </div>
    </div>
    <div class="layui-form-item text-right">
      <!-- <button class="layui-btn" lay-submit lay-filter="processSubmit" id="processSubmit" style="display: none" type="button">保存基准书工艺流程卡</button> -->
      <button class="layui-btn" lay-submit lay-filter="bookSubmit" data-type="present" type="button">暂时保存</button>
      <button class="layui-btn" lay-submit lay-filter="bookSubmit" type="button">提交</button>
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
    </div>
  </div>
</form>
<script type="text/html" id="skuSelectDiv"></script>

<script type="text/html" id="testItemTableBar">
  <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="zhijianTableBar">
  <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="productProjectTableBar">
  <!-- <a class="layui-btn layui-btn-xs" lay-event="selectProduct">选择成品</a> -->
  <!-- <a class="layui-btn layui-btn-xs" lay-event="edit">编辑/详情</a> -->
  <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
  <!-- <a class="layui-btn layui-btn-xs" lay-event="checkSkuFun">删除</a> -->
</script>

<script type="text/html" id="checkSkuBar">
  <!-- <a class="layui-btn layui-btn-xs" lay-event="selectProduct">选择成品</a> -->
  <!-- {{# if(d.semiFinishedCode){ }} -->
  <!-- {{ d.semiFinishedCode }} -->
  <!-- {{# }else{ }} -->
  <!-- <a class="layui-btn layui-btn-xs" lay-event="checkSkuFun">选择工序物料</a> -->
  <!-- {{# } }} -->
  <a class="layui-btn layui-btn-xs" lay-event="checkSkuFun"> {{d.semiFinishedCode?d.semiFinishedCode:'选择工序物料'}} </a>
</script>
<!-- 质检表 -->

<!-- skuTableBar -->
<script type="text/html" id="skuTableBar">
  <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/javascript" src="../../../admin/assets/js/pdfobject.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/layui-soul-table/docs/soulTable.css" media="all" />
<!-- 或者 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-soul-table/docs/soulTable.css" media="all" />

<script>
  layui.use(["layer", "tableTreeDj", "upload", "treetable", "form", "table", "laydate", "admin", "element", "laytpl", "upload", "config", "soulTable"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var config = layui.config;
    var table = layui.table;
    var admin = layui.admin;
    var form = layui.form;
    var upload = layui.upload;
    var laydate = layui.laydate;
    var tableTree = layui.tableTreeDj;
    var treetable = layui.treetable;
    var element = layui.element;
    var soulTable = layui.soulTable;

    console.log("soulTable", soulTable);
    const nowData = { ...parentData };
    let formVal = {};
    let data = [];
    let tabIndex = 0;

    /**
     * 拖拽表格 进行排序
     * @param obj  当前拖拽对象
     * @param tableId  表的主键ID
     * @param updateUrl  更新数据的接口
     * @param weightField  排序字段
     */
    function rowDragDoneFunc(obj, tableId, updateUrl, weightField) {
      weightField = weightField || "weight";
      console.log(obj.row, "--obj.row");
      // 获取最新位置 前后数据的id
      var beforId = (afterId = 0);
      if (obj.newIndex > 0) {
        beforId = obj.cache[obj.newIndex - 1][tableId];
      }
      if (obj.newIndex < obj.cache.length - 1) {
        afterId = obj.cache[obj.newIndex + 1][tableId];
      }
      var data = {
        dragDone: 1, // 增加数据标识  方便后台接口进行判断
        id: obj.row[tableId],
        field: weightField,
        beforId,
        afterId
      };
      // 提交数据进行排序更新
      layui.$.post(updateUrl, data, function (res) {
        if (res.code) {
          layui.layer.msg(res.msg, { icon: 5 });
        } else {
          obj.row[weightField] = res.data;
          refreshTable();
        }
      });
    }
    const personnelWorkTypeRes = await admin.reqPro("production/productionPlan/admin/profession/list");
    console.log("personnelWorkTypeRes", personnelWorkTypeRes);

    const personnelWorkTypeList = personnelWorkTypeRes.data.map((v) => {
      return {
        value: v.id,
        label: v.professionName
      };
    });
    let treetableParms = {
      id: "#bomTreeTable",
      elem: "#bomTreeTable",
      data: [],
      treeIdName: "productDetailId", // id的字段名
      treePidName: "parentId",
      treeColIndex: 1, //层级关系展示在第几列
      treeSpid: "-1", //是否有最高父id没有-1表示
      page: false,
      cellMinWidth: 100,
      cols: [
        [
          { type: "numbers", title: "序号", fixed: "left" },
          { field: "productName", title: "BOM产品名称", width: 300 },
          { field: "productCode", title: "产品编号" },
          { field: "productSpec", title: "规格码" },
          { field: "productTypeName", title: "物资类别" },
          { field: "productAttrName", title: "产品性质" },
          { field: "inSkuUnitName", title: "计量单位" },
          {
            field: "inUnitCount",
            title: "需求数",
            templet: (d) => {
              return admin.setTableInput("inUnitCount", d.parentId == "-1", "inUnitCount")(d);
            }
          },
          {
            field: "remark",
            title: "描质检标准",
            templet: (d) => {
              return admin.setTableInput("remark", d.parentId == "-1", "remark")(d);
            }
          },
          {
            title: "操作",  
            align: "center",
            width: 160,
            templet: function (d) {
              return `<a class="layui-btn layui-btn-xs" type="button" lay-event="addChild">添加子集</a>
                           <a class="layui-btn layui-btn-xs layui-btn-danger" type="button" lay-event="del">删除</a>`;
            }
          }
        ]
      ],
      done: function () {
        admin.tableInputChange("#bomTreeTable");
      }
    };
    treetable.render({ ...treetableParms });

    if (nowData.eventName === "detail") {
      admin.setFormDisable("#benchmarkBookFormModel", true);
      $("#addTestItem").hide();
      $("#fileUploadMoldBtn").hide();
      $("#moldUploadInfoBtn").hide();
    }
    console.log("nowData", nowData);

    if (nowData.data.status == 2) {
      console.log(333);

      $("#checkProcess").hide();
      $("#moldUploadInfoBtn").hide();
    }

    let projectTableData = []; //工序数据
    // 设置工序编码
    function setTableCode(list = table.cache["productProjectTable"]) {
      console.log("list", list);

      let skuCode = table.cache["benchmarkBookFormTable"][0].skuCode;
      list.forEach((v, i) => {
        v.code = skuCode + "-" + v.processNumber;
      });

      table.reload("productProjectTable", {
        data: iniList([...list])
      });
    }
    // 初始化工艺模板
    await admin.initDataSelectPro("enterprise/product/admin/processLineTemplate/list?page=1&limit=999", {}, "templateId", "模板", (d, obj) => {
      if (d.value) {
        //查询工艺模板关联的工序
        admin.req(
          "enterprise/product/admin/processLineTemplate/listAndProcess",
          {
            type: 1,
            templateId: d.value,
            page: 1,
            limit: 9999,
            sort: "sort_number",
            order: "asc"
          },
          function (res) {
            if (res.code == 200) {
              projectTableData = res.data.map((v) => {
                if (v.deviceType) {
                  v.deviceTypeName = 1;
                }
                if (v.productItems) {
                  // 筛选不启用的检测项
                  v.qualityList = [...v.productItems]
                    .filter((v) => {
                      return !v.isDeleted;
                    })
                    .map((v1) => {
                      v1.way = v1.qualityWayId;
                      v1.utensil = v1.deviceModelSpuId;
                      v1.importance = v1.importanceCode;
                      v1.no = v1.code;
                      return v1;
                    });
                }
                return {
                  ...v,
                  name: v.nodeNames,
                  code: table.cache["benchmarkBookFormTable"][0].skuCode + "-" + v.sortNumber,
                  processNumber: v.sortNumber,
                  content: v.remark,
                  qualityParam: "",
                  fixture: "",
                  measuringTools: "",
                  hoursQuota: "",
                  salaryQuota: "",
                  chengpin: "",
                  qualityType: "0"

                  // skuGetCode: ""
                };
              });
              console.log("projectTableData", projectTableData);

              table.reload("productProjectTable", {
                data: iniList(projectTableData)
              });
            }
          }
        );
      }
    });
    // 初始化基准书详情
    if (nowData.eventName === "add") {
      if (nowData.data.id) {
        admin.setFormDisable("#gy", true);
        const res = await admin.reqPro("enterprise/res/admin/planning/proTask/detail/" + nowData.data.id, {});
        data = res.data;
        const resBomList = await admin.reqPro("enterprise/res/admin/planning/proBom/bomTree/" + data.productDetailId, {});
        formVal = {
          ...data,
          resTaskId: data.id,
          source: data.source === "客户订单" ? 1 : 2,
          productType: data.productTypeId,
          productTypeName: data.productTypeName,
          materialNature: data.assemblyNature,
          materialNatureName: data.productNatureName,
          productAttr: data.productNature,
          productAttrName: data.assemblyNatureName,
          drawName: data.drawInfo?.name,
          drawUrl: data.drawInfo?.fileUrl,
          isRelevance: data.drawInfo?.isRelevance,
          skuCode: data.inSkuCode,
          skuName: data.inSkuName,
          skuSpec: data.inSkuSpec,
          remark: data.inRemark,
          drawMoldName: data.drawInfo?.moldDrawInfo?.name,
          drawMoldUrl: data.drawInfo?.moldDrawInfo?.fileUrl,
          drawMoldRemark: data.drawInfo?.moldDrawInfo?.remark,
          qualityList: data.testItemData.map((v) => {
            v.code = v.code;
            return v;
          }),
          echnologyList: data.processProjectData.map((v) => {
            v.code = v.code;
            return v;
          }),
          processLineTemplate: data.processProjectData.length > 0 ? data.processProjectData[0].templateId : "",
          bomList: resBomList.data.map((v) => {
            v.skuCode = v.productCode;
            v.count = v.inUnitCount;
            v.hasChild = v.hasChild ? 1 : 0;
            v.hasChild = v.hasEnableChild ? 1 : 0;
            v.parentId = resBomList.data.find((v1) => v1.bomId === v.parentId) ? resBomList.data.find((v1) => v1.bomId === v.parentId).productDetailId : data.productDetailId;
            v.id = v.productDetailId;
            return v;
          })
        };
        treetableParms.data = formVal.bomList;
        treetableParms.treeSpid = formVal.productDetailId;
        treetable.render(treetableParms);
      } else {
        formVal = { ...nowData.data };
        formVal.resTaskId = "-1";
        if (nowData.data && nowData.data.productDetailId) {
          formVal.bomList = [
            {
              id: nowData.data.productDetailId,
              productDetailId: nowData.data.productDetailId,
              productName: nowData.data.skuName,
              productCode: nowData.data.skuCode,
              productSpec: nowData.data.skuSpec,
              productTypeName: nowData.data.productTypeCode,
              productAttrName: nowData.data.productAttrName,
              inSkuUnitName: nowData.data.mainUnitName,
              parentId: "-1"
            }
          ];
        

          treetableParms.data = formVal.bomList;
          treetableParms.treeSpid = "-1";
          treetable.reload(treetableParms);
        } else {
          formVal.bomList = [];
        }
        formVal.echnologyList = [];
        formVal.qualityList = [];
      }
    } else {
      const res = await admin.reqPro("enterprise/benchmarkBook/admin/benchmarkBook/detail/" + nowData.data.id, {});
      data = res.data;
      data.bomList.forEach((v) => (v.id = v.productDetailId));
      formVal = { ...data };
      treetableParms.data = formVal.bomList;
      treetableParms.treeSpid = "-1";
      
      treetable.render(treetableParms);
    }

    if (formVal.drawUrl) {
      if (formVal.drawUrl && formVal.drawUrl.indexOf(".pdf") !== -1) {
        $("#drawImage").height(1000);
        PDFObject.embed(formVal.drawUrl, "#drawImage");
      } else {
        $("#drawImage").height("auto");
        $("#drawImage").html('<img style="max-width: 100%;max-height: 100%" src="' + formVal.drawUrl + '"/>');
      }
    }
    upload.render({
      elem: "#drawImageBtn",
      url: config.upload_url + "uploadFile",
      multiple: true,
      data: {},
      accept: "file",
      exts: "jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx",
      headers: { Authorization: "Bearer " + config.getToken() },
      done: function (res) {
        if (res.code == 200) {
          console.log(123, res.data);
          let list = table.cache["drawImageTable"];
          list.push({
            drawUrl: res.data.url,
            drawName: res.data.fileName
          });
          table.reload("drawImageTable", {
            data: list
          });
          // formVal.drawMoldUrl = res.data.url;
          // form.val("proTaskForm", {
          //   drawUrl: res.data.url,
          //   drawName: res.data.fileName,
          // });
          // if (res.data.url && res.data.url.indexOf(".pdf") !== -1) {
          //   $("#drawImage").height(1000);
          //   PDFObject.embed(res.data.url, "#drawImage");
          // } else {
          //   $("#drawImage").html(
          //     '<img style="width: 100%;height: 100%" src="' +
          //       res.data.url +
          //       '"/>'
          //   );
          //   $("#drawImage").height("auto");
          // }
          // $("#fileUploadMoldBtnText").html(res.data.fileName);
        } else if (res.code == 502) {
          return location.replace("admin/login.html");
        } else {
          layer.msg(res.msg || "上传失败", { icon: 2 });
        }
      }
    });

    $("#checkImageBtn").click(function () {
      // if (!table.cache["benchmarkBookFormTable"][0].skuCode) {
      //   layer.msg("请先选择物料", { icon: 2 });
      //   return;
      // }
      admin.formOpen({
        title: "选择图纸",
        area: "90%",
        offset: "50px",
        // path: "components/res/draw/proDraw.html",
        path: "components/res/draw/proDrawPic.html",
        success: function () {
          parentData.eventName = "radio";
          parentData.where = {
            productDetailId: form.val("proTaskForm").productDetailId
          };
          console.log(parentData);
        },
        end: function () {
          if (childData.list && childData.list.length > 0) {
            let obj = childData.list[0];
            let list = table.cache["drawImageTable"];
            list.push({
              drawUrl: obj.fileUrl,
              drawName: obj.name
            });
            table.reload("drawImageTable", {
              data: list
            });
            // form.val("proTaskForm", {
            //   drawUrl: obj.fileUrl,
            // });
            // if (obj.fileUrl && obj.fileUrl.indexOf(".pdf") !== -1) {
            //   $("#drawImage").height(1000);
            //   PDFObject.embed(obj.fileUrl, "#drawImage");
            // } else {
            //   $("#drawImage").html(
            //     '<img style="width: 100%;height: 100%" src="' +
            //       obj.fileUrl +
            //       '"/>'
            //   );
            //   $("#drawImage").height("auto");
            // }
            // projectTableData[index].deviceType = obj.id;
            // projectTableData[index].deviceTypeName = obj.name;
            // table.reload("productProjectTable", {
            //   data: projectTableData,
            // });
          }
        }
      });
    });
    // tab选择事件
    element.on("tab(test-handle)", function (data) {
      tabIndex = data.index;
      if (tabIndex == 2) {
        $("#processSubmit").show();
        table.reload("productProjectTable", {
          data: [...table.cache["productProjectTable"]]
        });
      } else {
        $("#processSubmit").hide();
      }
      if (tabIndex == 3) {
        table.reload("zhiliangTable", {
          data: [...table.cache["productProjectTable"]]
        });
      }
      if (tabIndex == 4) {
        table.reload("wuliaoTable", {
          data: [...table.cache["productProjectTable"]]
        });
      }
      if (tabIndex == 5) {
        table.reload("gongziTable", {
          data: [...table.cache["productProjectTable"]]
        });
      }
    });
    // 渲染模具图纸图片
    if (formVal.drawMoldUrl) {
      $("#modelImage").html('<img style="max-width: 100%;max-height: 100%" src="' + formVal.drawMoldUrl + '"/>');
      $("#fileUploadMoldBtnText").html(formVal.drawMoldName);
    } else {
      $("#modelImage").html("<div>暂无图片</div>");
    }
    form.val("proTaskForm", formVal);
    let drawInfos = [];
    if (data && data.id) {
      drawInfos = data.drawInfos ? data.drawInfos : [];
    }
    // 图片表格
    table.render({
      elem: "#drawImageTable",
      data: drawInfos ? [...drawInfos] : [],
      height: 480,
      page: false,
      cols: [
        [
          { type: "numbers", title: "序号" },
          { field: "drawName", title: "图片名称" },
          {
            field: "drawType",
            title: "图纸类别",
            templet: admin.setTableSelect(
              "drawType",
              [
                { value: 1, label: "成品图纸" },
                { value: 2, label: "工序图纸" },
                { value: 3, label: "模具图纸" },
                { value: 4, label: "夹治具图纸" },
                { value: 5, label: "其他图纸" }
              ],
              false,
              "drawType"
            )
          },
          // { field: "drawUrl", title: "图片地址" },
          {
            title: "操作",
            align: "center",
            width: 160,
            templet: function (d) {
              return `<a class="layui-btn layui-btn-xs" type="button" lay-event="preview">预览</a><a class="layui-btn layui-btn-xs" type="button" lay-event="del">删除</a>`;
            }
          }
        ]
      ],
      done: function () {
        admin.tableSelectChange("drawImageTable", "drawType");
      }
    });
    // 渲染头部表格
    table.render({
      elem: "#benchmarkBookFormTable",
      data: [{ ...formVal }],
      page: false,
      cellMinWidth: 100,
      cols: [
        [
          { type: "numbers", title: "序号" },
          {
            field: "code",
            title: "基准书编号",
            hide: nowData.eventName === "add",
            width: 160
          },
          {
            field: "bookType",
            title: "基准书类型",
            templet: admin.setTableSelect(
              "bookType",
              [
                { value: "1", label: "打样基准书" },
                { value: "2", label: "正式基准书" }
              ],
              nowData.eventName != "add",
              "bookType"
            )
          },
          {
            field: "skuCode",
            title: "sku料号",
            templet: (d) => {
              if (d.skuCode) {
                return d.skuCode;
              } else {
                return `<button class="layui-btn layui-btn-xs" type="button" id="skuCheck">选择sku</button>`;
              }
            }
          },
          { field: "skuName", title: "sku名称" },
          { field: "skuSpec", title: "规格码" },
          { field: "productTypeName", title: "产品类别" },
          { field: "materialNatureName", title: "产品性质" },
          { field: "productAttrName", title: "产品属性" },
          {
            field: "statusName",
            title: "状态",
            hide: nowData.eventName === "add"
          },
          {
            field: "creator",
            title: "提交人",
            hide: nowData.eventName === "add"
          },
          {
            field: "createTime",
            title: "提交时间",
            hide: nowData.eventName === "add"
          }
        ]
      ],
      done: function () {
        $(
          "#benchmarkBookForm .layui-table-body, .layui-table-box" // .layui-table-cell
        ).css("overflow", "visible");
        admin.tableSelectChange("benchmarkBookFormTable", "bookType");
        admin.tableSelectChange("benchmarkBookFormTable", "bookType");
      }
    });
    $("#skuCheck").click(function () {
      admin.formOpen({
        area: ["90%", "90%"],
        offset: "25px",
        title: "选择sku",
        path: "components/res/benchmarkBook/bookSkuTable.html",

        success: function () {},
        end: function () {
          if (childData.skuObj) {
            let skuObj = childData.skuObj;
            let objData = {
              code: "",
              resTaskId: "-1",
              skuCode: skuObj.skuCode,
              skuName: skuObj.skuName,
              skuSpec: skuObj.skuSpec,
              productDetailId: skuObj.id,
              source: "",
              productType: skuObj.productTypeId,
              productTypeName: skuObj.productTypeName,
              materialNature: skuObj.materialNature,
              materialNatureName: skuObj.materialNatureName,
              productAttr: skuObj.productNature,
              productAttrName: skuObj.productNatureName,
              remark: skuObj.remark,
              drawName: "",
              drawUrl: "",
              isRelevance: "",
              drawMoldName: "",
              drawMoldUrl: "",
              bookType: table.cache["benchmarkBookFormTable"][0].bookType,
              bookType: table.cache["benchmarkBookFormTable"][0].bookType
            };
            form.val("proTaskForm", { ...objData });
            table.reload("benchmarkBookFormTable", {
              data: [{ ...objData }]
            });
            table.cache["productProjectTable"] = table.cache["productProjectTable"].map((v) => {
              v.code = skuObj.skuCode + "-" + v.processNumber;
              return v;
            });
            let bomObj = {
              id: skuObj.id,
              productDetailId: skuObj.id,
              productName: skuObj.skuName,
              productCode: skuObj.skuCode,
              productSpec: skuObj.skuSpec,
              productTypeName: skuObj.productTypeName,
              productAttrName: skuObj.productAttrName,
              inSkuUnitName: skuObj.mainUnitName,
              parentId: "-1",
              bookType: table.cache["benchmarkBookFormTable"][0].bookType,
              bookType: table.cache["benchmarkBookFormTable"][0].bookType
            };
            treetableParms.data = [bomObj];
            formVal.bomList = [bomObj];
            treetableParms.treeSpid = "-1";
            treetable.reload(treetableParms);
            setTableCode();
          }
        }
      });
      return false;
    });

    // 初始化质检管理
    table.render({
      elem: "#testItemTable",
      data: [...formVal.qualityList],
      id: "testItemTable",
      limit: 9999,
      cols: [
        [
          { type: "numbers", title: "序号" },
          {
            field: "name",
            align: "center",
            title: "检查项",
            templet: admin.setTableInput("name", nowData.eventName === "detail")
          },
          {
            field: "standard",
            sort: true,
            title: "标准",
            templet: admin.setTableInput("standard", nowData.eventName === "detail")
          },
          {
            field: "utensil",
            sort: true,
            title: "器具",
            templet: admin.setTableInput("utensil", nowData.eventName === "detail")
          },
          {
            field: "way",
            sort: true,
            title: "方法",
            templet: admin.setTableInput("way", nowData.eventName === "detail")
          },
          {
            field: "importance",
            sort: true,
            title: "重要程度",
            templet: admin.setTableInput("importance", nowData.eventName === "detail")
          },
          {
            field: "detectionRate",
            sort: true,
            title: "检测率",
            templet: admin.setTableInput("detectionRate", nowData.eventName === "detail")
          },
          {
            align: "center",
            toolbar: "#testItemTableBar",
            title: "操作",
            width: 160,
            hide: nowData.eventName === "detail"
          }
        ]
      ],
      done: function () {
        admin.tableInputChange("testItemTable");
      }
    });

    console.log("formVal", formVal);
    function iniList(lData) {
      var formSkuCode;
      if (nowData.eventName === "add") {
        if (form.val("proTaskForm").skuCode) {
          formSkuCode = form.val("proTaskForm").skuCode;
        }
      }
      if (lData.length === 0) {
        return [];
      }
      var code = lData[0].code.split("-")[0]; // 获取第一个元素的编码前缀
      if (formSkuCode) {
        code = formSkuCode;
      }
      console.log("lData", lData);
      lData.forEach((item, index) => {
        // item.processNumber = index + 1; // 设置排序号
        item.code = `${code}-${item.processNumber}`; // 设置编码

        if (index === 0) {
          item.type = "0"; // 首工序
        } else if (index === lData.length - 1) {
          item.type = "2"; // 末工序
        } else {
          item.type = "1"; // 过程工序
        }
      });
      return lData;
    }

    console.log("formVal", formVal);
    //初始化工序表
    table.render({
      elem: "#productProjectTable",
      data: [...formVal.echnologyList],
      id: "productProjectTable",
      limit: 9999,
      height: "480",
      // page: false,
      cols: [
        [
          { type: "numbers", title: "序号" },
          {
            field: "name",
            title: "工序名称",
            templet: admin.setTableInput("name", nowData.eventName == "detail" || Number(formVal.status) >= 2, "name")
          },
          {
            field: "processNumber",
            title: "工序号",
            templet: admin.setTableInput("processNumber", nowData.eventName == "detail" || Number(formVal.status) >= 2, "processNumber")
          },
          {
            field: "code",
            title: "工序编码",
            templet: admin.setTableInput("code", true, "code")
          },

          // { field: "processNumber", title: "工序排序", hide: true },
          {
            field: "type",
            title: "工序属性",
            templet: admin.setTableSelect(
              "type",
              [
                { value: 0, label: "首工序" },
                { value: 1, label: "过程工序" },
                { value: 2, label: "末工序" }
              ],
              true,
              "type"
            )
          },
          {
            field: "content",
            title: "工序工艺要求",
            width: 200,
            templet: admin.setTableInput("content", nowData.eventName === "detail")
          },
          // {
          //   field: "fixture",
          //   title: "夹具",
          //   width: 80,
          //   templet: admin.setTableInput(
          //     "fixture",
          //     nowData.eventName === "detail"
          //   ),
          // },
          // {
          //   field: "measuringTools",
          //   title: "量具",
          //   width: 80,
          //   templet: admin.setTableInput(
          //     "measuringTools",
          //     nowData.eventName === "detail"
          //   ),
          // },
          {
            field: "hoursQuota",
            title: "工时定额(分钟)",
            templet: admin.setTableInput("hoursQuota", nowData.eventName === "detail")
          },
          {
            field: "personnelWorkType",
            title: "人员工种",
            templet: admin.setTableSelect("personnelWorkType", personnelWorkTypeList)
          },
          {
            field: "workstationNature",
            title: "工位性质",
            templet: admin.setTableSelect(
              "workstationNature",
              [
                // { value: 0, label: "人工工位" },
                { value: 1, label: "设备工位" },
                { value: 2, label: "人工工位" }
              ],
              nowData.eventName === "detail",
              "workstationNature"
            )
          },
          // {
          //   field: "salaryQuota",
          //   title: "工资定额(元)",
          //   templet: admin.setTableInput(
          //     "salaryQuota",
          //     nowData.eventName === "detail",
          //     "salaryQuota"
          //   ),
          // },
          // {
          //   field: "ngSalaryQuota",
          //   title: "NG工资定额",
          //   templet: admin.setTableInput(
          //     "ngSalaryQuota",
          //     nowData.eventName === "detail",
          //     "ngSalaryQuota"
          //   ),
          // },

          // {
          //   title: "成品料号",
          //   toolbar: "#checkSkuBar",
          // },
          {
            title: "工种/机型",
            templet: function (d) {
              return `  <a class="layui-btn layui-btn-xs" lay-event="deviceFun">${d.deviceType ? d.deviceTypeName : "选择数据"}</a>`;
            }
          },
          {
            toolbar: "#productProjectTableBar",
            title: "操作",
            hide: nowData.eventName === "detail"
          }
        ]
      ],

      rowDrag: {
        /*trigger: 'row',*/ done: function (obj) {
          // 完成时（松开时）触发
          // 如果拖动前和拖动后无变化，则不会触发此方法
          // 拖动完成后自动设置工序属性
          const rowData = obj.cache;

          // 重新渲染表格
          table.reload("productProjectTable", {
            data: iniList(rowData)
          });

          console.log(obj.row); // 当前行数据
          console.log(obj.cache); // 改动后全表数据
          console.log(obj.oldIndex); // 原来的数据索引
          console.log(obj.newIndex); // 改动后数据索引
        }
      },
      totalRow: true,
      done: function () {
        if (nowData.eventName !== "detail") {
          soulTable.render(this);
        }

        admin.tableInputChange("productProjectTable");
        projectTableData = table.cache["productProjectTable"];
        admin.tableSelectChange("productProjectTable", "workstationNature", (index) => {
          table.cache["productProjectTable"][index].deviceType = "";
          table.cache["productProjectTable"][index].deviceTypeName = "";
          table.reload("productProjectTable", {
            data: table.cache["productProjectTable"]
          });
        });
        admin.tableSelectChange("productProjectTable", "type", (index, value, tableData) => {
          console.log(tableData.filter((v) => v.type === "0"));
          console.log(tableData.filter((v) => v.type === "2"));

          if (tableData.filter((v) => v.type === "0").length > 1) {
            layer.msg("首工序只能有一个", { icon: 2 });
            table.cache["productProjectTable"][index].type ? (table.cache["productProjectTable"][index].type = "") : "";
          } else if (tableData.filter((v) => v.type == "2").length > 1) {
            layer.msg("末工序只能有一个", { icon: 2 });
            table.cache["productProjectTable"][index].type ? (table.cache["productProjectTable"][index].type = "") : "";
          }
          table.reload("productProjectTable", {
            data: table.cache["productProjectTable"]
          });
        });
        admin.tableInputChangeByClass("productProjectTable", "processNumber", (index) => {
          let skuCode = table.cache["benchmarkBookFormTable"][0].skuCode;
          let processNumber = projectTableData[index].processNumber;
          let code = skuCode + "-" + processNumber;
          table.cache["productProjectTable"][index].code = code;
          admin.setTableColHtml("productProjectTable", index, "code", code);
        });
        admin.tableInputChangeByClass("skuTable", "quantity", (index) => {
          let productProjectTableList = table.cache["productProjectTable"];
          let list = table.cache["skuTable"];
          let quantity = list[index].quantity;
          productProjectTableList[productProjectTableIndex].skuList[index].quantity = quantity;
          table.reload("productProjectTable", {
            data: productProjectTableList
          });
        });
      }
    });

    $("#benchmarkBookFormModel .layui-table-body").css("overflow", "visible");
    $("#benchmarkBookFormModel .layui-table-box").css("overflow", "visible");
    $("#benchmarkBookFormModel .layui-table-view").css("overflow", "visible");
    // admin.tableInputChangeByClass(
    //   "productProjectTable",
    //   "name",
    //   (index) => {}
    // );
    admin.setFormDisable("#processFormContent", true);

    // 初始化物料管理
    table.render({
      elem: "#wuliaoTable",
      data: [...formVal.qualityList],
      id: "wuliaoTable",
      limit: 9999,
      cols: [
        [
          { field: "name", title: "工序名称" },
          { field: "processNumber", title: "产品工序号" },
          {
            field: "type",
            title: "工序属性",
            templet: admin.setTableSelect(
              "type",
              [
                { value: "", label: "-" },
                { value: 0, label: "首工序" },
                { value: 1, label: "过程工序" },
                { value: 2, label: "末工序" }
              ],
              true
            )
          },
          { field: "code", title: "产品工序编码" }
        ]
      ]
    });

    // 初始化质检管理
    table.render({
      elem: "#zhiliangTable",
      data: [],
      id: "zhiliangTable",
      height: "480", // 高度
      limit: 9999,

      cols: [
        [
          { type: "checkbox", fixed: "left", title: "选择" },
          { type: "numbers", title: "序号" },
          { field: "name", title: "工序名称" },
          // { field: "processNumber", title: "产品工序号" },
          // { field: "code", title: "产品工序编码" },
          {
            field: "type",
            title: "工序属性",
            templet: admin.setTableSelect(
              "type",
              [
                { value: "", label: "-" },
                { value: 0, label: "首工序" },
                { value: 1, label: "过程工序" },
                { value: 2, label: "末工序" }
              ],
              true
            )
          },
          // {
          //   field: "qualityType",
          //   title: "是否质检",
          //   templet: admin.setTableSelect(
          //     "qualityType",
          //     [
          //       { value: 0, label: "不需要质检" },
          //       { value: 1, label: "抽检" },
          //       { value: 2, label: "全检" },
          //     ],
          //     true
          //   ),
          // },
          {
            field: "qualityType",
            title: "是否质检",
            templet: admin.setTableSelect(
              "qualityType",
              [
                { value: 0, label: "不质检" },
                { value: 1, label: "质检" }
              ],
              nowData.eventName === "detail",
              "qualityType"
            )
          },
          {
            field: "qualityAttributes",
            title: "是否质检",
            templet: (d) => {
              if (d.qualityType == 0) {
                return "-";
              }
              return admin.setTableSelect(
                "qualityAttributes",
                [
                  { value: 1, label: "一物一检" },
                  { value: 2, label: "简易检测" }
                ],
                nowData.eventName === "detail",
                "qualityAttributes"
              )(d);
            }
          }
          // {
          //   field: "qualityNature",
          //   title: "质检方式",
          //   templet: admin.setTableSelect(
          //     "qualityNature",
          //     [
          //       { value: 0, label: "不需要质检验" },
          //       { value: 1, label: "普通检验" },
          //       { value: 2, label: "一物一检" },
          //     ],
          //     nowData.eventName === "detail"
          //   ),
          // },
          // { title: "成品料号", field: "semiFinishedCode" },
        ]
      ],
      done: function () {
        console.log(1111);
        $('input[name="layTableCheckbox"]').attr("disabled", "disabled");
        admin.tableSelectChange("zhiliangTable", "qualityType", (index, value, tableData, field, tableId) => {
          let obj = table.cache["productProjectTable"][index];
          obj.qualityType = value;
          // console.log(1111, obj.qualityType);
          if (obj.qualityType == 1) {
            $("#addZhijian").show();
          } else {
            $("#addZhijian").hide();
          }
          table.reload("zhiliangTable", {});
          // if (obj.qualityType == 1 || obj.qualityType == 2) {
          //   $("#addZhijian").show();
          //   table.reload("zhijianTable", {
          //     data: obj.qualityList || [],
          //   });
          // } else {
          //   $("#addZhijian").hide();
          //   table.reload("zhijianTable", {
          //     data: [],
          //   });
          // }
          // console.log(222, table.cache["zhiliangTable"]);

          // table.reload("zhiliangTable", {
          //   data: table.cache["zhiliangTable"],
          // });
        });
        admin.tableSelectChange("zhiliangTable", "qualityAttributes", (index, value, tableData, field, tableId) => {
          let obj = table.cache["productProjectTable"][index];
          obj.qualityAttributes = value;
        });
      }
    });

    let productProjectTableIndex = 0;
    let zhijianTableIndex = 0;
    $("#addZhijian").click(function () {
      table.reload("zhijianTable", {
        data: [...table.cache["zhijianTable"], {}]
      });
      table.cache["zhiliangTable"] = zhiliangList;
      table.reload("zhiliangTable", {
        data: table.cache["zhiliangTable"]
      });
      console.log(table.cache["zhiliangTable"]);
    });
    $("#addSku").hide();
    $("#addSku").click(function () {
      admin.formOpen({
        area: "90%",
        offset: "50px",
        title: "配置物料清单",
        path: "components/purchase/skuTableForm.html",
        success: function () {
          parentData.notInListIds = table.cache["skuTable"].map((v) => v.productDetailId).join(",");
        },
        end: function () {
          if (childData.list) {
            const newData = childData.list || [];
            const oldData = table.cache["skuTable"];
            const list = [...oldData, ...newData];
            table.reload("skuTable", {
              data: list // 设置新的数据
            });
          }
        }
      });
    });
    $("#addSkuByBom").click(function () {
      admin.formOpen({
        area: "90%",
        offset: "50px",
        title: "配置物料清单",
        path: "components/purchase/skuTableForm.html",
        success: function () {
          let list = table.cache["#bomTreeTable"].filter((v1, i1) => i1 != 0);
          if (list.length == 0) {
            list = [{ productDetailId: -1 }];
          }
          parentData.where = {
            inIds: list.map((v) => v.productDetailId).join(","),
            notInListIds: table.cache["skuTable"].map((v) => v.productDetailId).join(",")
          };
        },
        end: function () {
          if (childData.list && childData.list.length > 0) {
            let bomList = table.cache["#bomTreeTable"];
            console.log(123, bomList);

            let newData = childData.list.map((v) => {
              let obj = bomList.find((v1) => v1.productDetailId == v.productDetailId);
              console.log(obj);

              if (obj) {
                v.quantity = obj.inUnitCount;
              }
              return v;
            });
            console.log(333, newData);
            const oldData = table.cache["skuTable"];
            const list = [...oldData, ...newData];
            console.log(111, list);

            table.reload("skuTable", {
              data: list // 设置新的数据
            });
          }
        }
      });
    });

    if (table.cache["productProjectTable"].length > 0) {
      form.val("proTaskForm", {
        content: table.cache["productProjectTable"][productProjectTableIndex].content,
        fixture: table.cache["productProjectTable"][productProjectTableIndex].fixture,
        measuringTools: table.cache["productProjectTable"][productProjectTableIndex].measuringTools,
        unitId: table.cache["productProjectTable"][productProjectTableIndex].unitId,
        hoursQuota: table.cache["productProjectTable"][productProjectTableIndex].hoursQuota,
        salaryQuota: table.cache["productProjectTable"][productProjectTableIndex].salaryQuota,
        ngSalaryQuota: table.cache["productProjectTable"][productProjectTableIndex].salaryQuota,
        qualityType: table.cache["productProjectTable"][productProjectTableIndex].qualityType ? table.cache["productProjectTable"][productProjectTableIndex].qualityType : 0
      });
    }
    if (nowData.eventName != "detail") {
      admin.setFormDisable("#processFormContent", false);
      $("#addSku").show();
    }
    $("#addLastSku").click(function () {
      let index = productProjectTableIndex;
      if (index == 0) {
        layer.msg("没有上个工序");
        return;
      } else {
        let lastObj = table.cache["productProjectTable"][index - 1];
        if (!lastObj.semiFinishedId || lastObj.semiFinishedId == "" || lastObj.semiFinishedId == "0") {
          layer.msg("上个工序没有产成品");
          return;
        }
        let skuCode = {
          skuCode: lastObj.semiFinishedCode,
          skuName: lastObj.semiFinishedName,
          productDetailId: lastObj.semiFinishedId
        };
        let list = table.cache["skuTable"];
        if (list.some((v) => v.productDetailId === skuCode.productDetailId)) {
          layer.msg("该物料已存在");
          return;
        } else {
          list.push(skuCode);
          table.reload("skuTable", {
            data: list
          });
        }
      }
    });
    // table.reload("skuTable", {
    //   data: data.skuList || []
    // });
    var zhiliangList;

    $("#processFormContent input,textarea").on("input", function () {
      let list = table.cache["productProjectTable"];
      let name = $(this).attr("name");
      list[productProjectTableIndex][name] = $(this).val();
      table.reload("productProjectTable", { data: list });
    });

    table.on("row(wuliaoTable)", function (obj) {
      // let list = table.cache["productProjectTable"];
      if ($(event.target).is("input,select,textarea")) {
        return; // 如果是输入框，直接返回，不执行后续代码
      }
      var data = obj.data; // 获取当前行数据

      const index = $(obj.tr[0]).data("index");
      if (nowData.eventName != "detail") {
        admin.setFormDisable("#processFormContent", false);
        $("#addSku").show();
      }
      productProjectTableIndex = index;
      table.reload("skuTable", {
        data: data.skuList || []
      });
      return false;
    });
    table.on("row(zhiliangTable)", function (obj) {
      var data = obj.data; // 获取当前行数据
      // 显示 - 仅用于演示

      // let list = table.cache["productProjectTable"];
      if ($(event.target).is("input,select,textarea")) {
        return; // 如果是输入框，直接返回，不执行后续代码
      }

      console.log("data", data);
      console.log("qualityType", table.cache["zhiliangTable"]);

      const index = $(obj.tr[0]).data("index");
      zhijianTableIndex = index;
      if (data.qualityType == 1 || data.qualityType == 2) {
        $("#addZhijian").show();
        table.reload("zhijianTable", {
          data: data.qualityList || []
        });
      } else {
        $("#addZhijian").hide();
        table.reload("zhijianTable", {
          data: []
        });
      }
      //  else {
      //   $("#addZhijian").hide();
      //   table.reload("zhijianTable", {
      //     data: [],
      //   });
      // }
      // if (nowData.eventName != "detail") {
      //   admin.setFormDisable("#processFormContent", false);
      //   $("#addSku").show();
      // }
      // 标注当前点击行的选中状态
      // obj.setRowChecked({
      //   type: 'radio' // radio 单选模式；checkbox 复选模式
      // });
      var tableData = table.cache["zhiliangTable"]; // 获取当前表格的所有数据
      const iIndex = tableData.findIndex((item) => item.id === obj.data.id);
      if (!tableData[iIndex].name) {
        layer.msg("请先添加工序名");
        return;
      }

      if (tableData[iIndex].LAY_CHECKED) {
        tableData[iIndex].LAY_CHECKED = false; // Uncheck the current row
      } else {
        // First, set all rows to false
        tableData.forEach((item) => {
          item.LAY_CHECKED = false;
        });
        // Then set only the current row to true

        tableData[iIndex].LAY_CHECKED = true;
      }
      console.log(" tableData[iIndex].LAY_CHECKED", tableData[iIndex].LAY_CHECKED);

      console.log("obj:", obj); // 输出当前行的索引
      zhiliangList = tableData;
      table.reload("zhiliangTable", {
        // 重新渲染表格
        data: tableData // 将更新后的数据传递给表格
      });

      return false;
    });

    let skuTableData = [];
    let zhijianTableData = [];
    if (table.cache["productProjectTable"].length > 0) {
      skuTableData = table.cache["productProjectTable"][productProjectTableIndex].skuList;
      zhijianTableData = table.cache["productProjectTable"][productProjectTableIndex].qualityList;
    }
    //检测分类
    const itemCategoryRes = await admin.reqPro("production/qualityTesting/admin/qualityTestingCategory/list", { limit: 9999 });
    const itemCategoryList = itemCategoryRes.data;
    //检测类型
    const itemTypeRes = await admin.reqPro("enterprise/dict/admin/dictLabel/select", { dictType: "sys_qc_quality_type" });
    const itemTypeList = itemTypeRes.data;
    //质检方法
    const qualityWayRes = await admin.reqPro("enterprise/dict/admin/dictLabel/select", { dictType: "sys_detection_method" });
    const qualityWayList = qualityWayRes.data;
    // 质检设备
    const deviceModelSpuRes = await admin.reqPro("enterprise/device/admin/deviceModel/list", { limit: 9999 });
    const deviceModelSpuList = deviceModelSpuRes.data;
    // 重要程度
    const importanceRes = await admin.reqPro("enterprise/dict/admin/dictLabel/select", { dictType: "pro_importance_type" });
    const importanceList = importanceRes.data;
    console.log(importanceList);

    table.render({
      elem: "#zhijianTable",
      data: zhijianTableData ? [...zhijianTableData] : [],
      id: "zhijianTable",
      height: "480", // 高度
      limit: 9999,
      cols: [
        [
          // { type: "numbers", title: "序号" },
          // {
          //   field: "name",
          //   align: "center",
          //   title: "检查项",
          //   templet: admin.setTableInput(
          //     "name",
          //     nowData.eventName === "detail",
          //     "name"
          //   ),
          // },
          // {
          //   field: "standard",
          //   title: "标准",
          //   templet: admin.setTableInput(
          //     "standard",
          //     nowData.eventName === "detail",
          //     "standard"
          //   ),
          // },
          // {
          //   field: "utensil",
          //   title: "器具",
          //   templet: admin.setTableInput(
          //     "utensil",
          //     nowData.eventName === "detail",
          //     "utensil"
          //   ),
          // },
          // {
          //   field: "way",
          //   title: "方法",
          //   templet: admin.setTableInput(
          //     "way",
          //     nowData.eventName === "detail",
          //     "way"
          //   ),
          // },
          // {
          //   field: "importance",
          //   title: "重要程度",
          //   templet: admin.setTableInput(
          //     "importance",
          //     nowData.eventName === "detail",
          //     "importance"
          //   ),
          // },
          // {
          //   field: "detectionRate",
          //   title: "检测率",
          //   templet: admin.setTableInput(
          //     "detectionRate",
          //     nowData.eventName === "detail",
          //     "detectionRate"
          //   ),
          // },
          { type: "numbers", title: "序号" },
          {
            field: "name",
            align: "center",
            title: "检测项",
            templet: admin.setTableInput("name", nowData.eventName === "detail", "name")
          },
          {
            field: "remark",
            align: "center",
            title: "质检标准",
            templet: admin.setTableInput("remark", nowData.eventName === "detail", "remark")
          },
          // {
          //   field: "no",
          //   align: "center",
          //   title: "检测项编码",
          //   templet: admin.setTableInput(
          //     "no",
          //     nowData.eventName === "detail",
          //     "no"
          //   ),
          // },
          {
            field: "itemCategoryId",
            align: "center",
            title: "检测分类",
            templet: admin.setTableSelect(
              "itemCategoryId",
              itemCategoryList.map((v) => ({ value: v.id, label: v.name })),
              false,
              "itemCategoryId"
            )
          },
          {
            field: "itemType",
            align: "center",
            title: "检测类型",
            templet: admin.setTableSelect(
              "itemType",
              itemTypeList.map((v) => ({
                value: v.labelValue,
                label: v.labelName
              })),
              false,
              "itemType"
            )
          },
          {
            field: "way",
            align: "center",
            title: "质检方法",
            templet: admin.setTableSelect(
              "way",
              qualityWayList.map((v) => ({
                value: v.labelValue,
                label: v.labelName
              })),
              false,
              "way"
            )
          },
          {
            field: "utensil",
            align: "center",
            title: "质检器具",
            templet: admin.setTableSelect(
              "utensil",
              deviceModelSpuList.map((v) => ({
                value: v.id,
                label: v.name
              })),
              false,
              "utensil"
            )
          },
          {
            field: "importance",
            align: "center",
            title: "重要程度",
            templet: admin.setTableSelect(
              "importance",
              importanceList.map((v) => ({
                value: v.labelValue,
                label: v.labelName
              })),
              false,
              "importance"
            )
          },

          {
            align: "center",
            toolbar: "#zhijianTableBar",
            title: "操作",
            width: 160,
            hide: nowData.eventName === "detail"
          }
        ]
      ],
      done: function () {
        function changeInputByzhijiann(name, value, index) {
          let obj = table.cache["productProjectTable"][zhijianTableIndex];
          let proObj = obj.qualityList[index];
          proObj[name] = value;
        }
        // admin.tableInputChange("zhijianTable")
        let nameList = ["name", "no", "standard", "utensil", "way", "importance", "detectionRate", "remark"];
        let nameListBySelect = ["itemCategoryId", "itemType", "way", "utensil", "importance"];
        nameListBySelect.forEach((name) => {
          admin.tableSelectChange("zhijianTable", name, (index, value, tableData, field, tableId) => {
            changeInputByzhijiann(name, value, index);
          });
        });
        nameList.forEach((name) => {
          admin.tableInputChangeByClass("zhijianTable", name, (index, value, tableData, field, tableId) => {
            changeInputByzhijiann(name, value, index);
          });
        });
        let list = table.cache["zhijianTable"];
        let productProjectTableList = table.cache["productProjectTable"];
        if (zhijianTableIndex >= 0 && productProjectTableList.length > 0) {
          productProjectTableList[zhijianTableIndex].qualityList = list;
          table.reload("productProjectTable", {
            data: productProjectTableList
          });
          table.reload("zhiliangTable", { data: productProjectTableList });
        }
      }
    });
    table.render({
      elem: "#skuTable",
      data: skuTableData ? [...skuTableData] : [],
      id: "skuTable",
      page: false,
      limit: Number.MAX_VALUE,
      cols: [
        [
          { type: "numbers", title: "序号" },
          { field: "skuName", title: "物料名称" },
          { field: "skuCode", title: "物料编码" },
          { field: "skuSpec", title: "物料规格码" },
          { title: "基础单位", field: "baseUnitName" },
          {
            field: "quantity",
            title: "预计所需数量(基础单位)",
            templet: admin.setTableInput("quantity", nowData.eventName === "detail", "quantity")
          },
          { field: "productDetailId", title: "物料ID", hide: true },
          { align: "center", toolbar: "#skuTableBar", title: "操作" }
        ]
      ],
      done: function () {
        let list = table.cache["skuTable"];
        let productProjectTableList = table.cache["productProjectTable"];
        if (productProjectTableIndex >= 0 && productProjectTableList.length > 0) {
          productProjectTableList[productProjectTableIndex].skuList = list;
          table.reload("productProjectTable", {
            data: productProjectTableList
          });
          table.reload("wuliaoTable", { data: productProjectTableList });
        }
      }
    });
    // 工序工资
    table.render({
      elem: "#gongziTable",
      data: [],
      id: "gongziTable",
      page: false,
      limit: Number.MAX_VALUE,
      cols: [
        // 序号	工序名称	产品工序号	产品工序编码	工序排序	工序属性	工时定额	OK计件工资定额	NG工资定额	报废定额	备注内容
        [
          { type: "numbers", title: "序号" },
          { field: "name", title: "工序名称" },
          { field: "processNumber", title: "产品工序号" },
          { field: "code", title: "产品工序编码" },
          {
            field: "type",
            title: "工序属性",
            templet: admin.setTableSelect(
              "type",
              [
                { value: "", label: "-" },
                { value: 0, label: "首工序" },
                { value: 1, label: "过程工序" },
                { value: 2, label: "末工序" }
              ],
              true
            )
          },
          {
            field: "hoursQuota",
            title: "工时定额"
          },
          {
            field: "unitId",
            title: "报工单位",
            templet: admin.setTableInput("unitId", nowData.eventName === "detail", "unitId")
          },
          {
            field: "salaryQuota",
            title: "OK计件工资定额",
            templet: admin.setTableInput("salaryQuota", nowData.eventName === "detail", "salaryQuota")
          },
          {
            field: "ngSalaryQuota",
            title: "NG工资定额",
            templet: admin.setTableInput("ngSalaryQuota", nowData.eventName === "detail", "ngSalaryQuota")
          },
          {
            field: "bfSalaryQuota",
            title: "报废定额",
            templet: admin.setTableInput("bfSalaryQuota", nowData.eventName === "detail", "bfSalaryQuota")
          },
          {
            field: "remark",
            title: "备注内容",
            templet: admin.setTableInput("remark", nowData.eventName === "detail", "remark")
          }
        ]
      ],
      done: function () {
        function changeInputBygongzi(name, value, index) {
          let obj = table.cache["productProjectTable"][index];
          obj[name] = value;
        }
        let nameList = [
          // "hoursQuota",
          "okSalaryQuota",
          "ngSalaryQuota",
          "bfSalaryQuota",
          "remark",
          "salaryQuota",
          "unitId"
        ];
        nameList.forEach((name) => {
          admin.tableInputChangeByClass("gongziTable", name, (index, value, tableData, field, tableId) => {
            changeInputBygongzi(name, value, index);
          });
        });
      }
    });
    table.on("tool(skuTable)", function (obj) {
      if (obj.event === "del") {
        let index = $(obj.tr[0]).data("index");
        let list = table.cache["skuTable"];

        list.splice(index, 1);
        table.reload("skuTable", { data: list });
      }
    });
    table.on("tool(drawImageTable)", function (obj) {
      if (obj.event === "preview") {
        let type = obj.data.drawUrl.split(".").pop();

        //           let content = "";
        //           if (type == "pdf") {
        //           } else {
        //             content = `<div id='drawImage' style='overflow: hidden;height:100%;display:flex;justify-content: center;
        // '><img style="height:100%" src="${obj.data.drawUrl}"/></div>`;
        //           }

        admin.formOpen({
          title: "图片预览",
          area: ["80%", "80%"],
          content: `<div id='drawImage' style='height:100%;display:flex;justify-content: center;
  '></div>`,
          success: function () {
            if (obj.data.drawUrl && obj.data.drawUrl.indexOf(".pdf") !== -1) {
              // $("#drawImage").height(1000);
              PDFObject.embed(obj.data.drawUrl, "#drawImage");
            } else {
              $("#drawImage").height("auto");
              $("#drawImage").html('<img style="max-width: 100%;max-height: 100%" src="' + obj.data.drawUrl + '"/>');
            }
          }
        });
      } else if (obj.event === "del") {
        let index = $(obj.tr[0]).data("index");

        let list = table.cache["drawImageTable"];
        list.splice(index, 1);
        table.reload("drawImageTable", { data: list });
      }
    });
    upload.render({
      elem: "#fileUploadMoldBtn",
      url: config.upload_url + "uploadFile",
      data: {},
      accept: "file",
      exts: "jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx",
      headers: { Authorization: "Bearer " + config.getToken() },
      done: function (res) {
        if (res.code == 200) {
          // formVal.drawMoldUrl = res.data.url;
          form.val("proTaskForm", {
            drawMoldUrl: res.data.url,
            drawMoldName: res.data.fileName
          });
          $("#modelImage").html('<img style="width: 100%;height: 100%" src="' + res.data.url + '"/>');
          $("#fileUploadMoldBtnText").html(res.data.fileName);
          // layer.msg(res.msg || '上传成功', { icon: 1 });
          // let imagUrl = res.data.url;
          // moldName = res.data.fileName;
          // fileName = res.data.fileName;
          // $('#addMoldHeaderPdf').html('<div class="moldAttachments">' + '<div><img name="moldAttachments" src="../../../admin/assets/images/attachmentsIcon/pdf.png"><span class="file-a">' + moldName + '</span></div></div>');
          // $('#attachmentMoldPdf').val(imagUrl);

          // $('.moldAttachments').click(function () {
          //   let json = {};
          //   json.attachment = imagUrl;
          //   showViewAttachmentModel(json);
          // });
        } else if (res.code == 502) {
          return location.replace("admin/login.html");
        } else {
          layer.msg(res.msg || "上传失败", { icon: 2 });
        }
      }
    });
    table.on("tool(productProjectTable)", function (obj) {
      const data = obj.data;
      const index = $(obj.tr[0]).data("index");
      if (obj.event === "del") {
        // formVal.echnologyList.splice(index, 1);
        // table.reload("productProjectTable", {
        //   data: [...formVal.echnologyList]
        // });

        // let list = table.cache["productProjectTable"];
        // list.splice(index, 1);
        // console.log(2,list);

        obj.del(); // 删除当前行
        // 获取表格数据
        projectTableData = projectTableData.filter((item) => Object.keys(item).length > 0);
        table.reload("productProjectTable", {
          data: iniList(projectTableData)
        });
      } else if (obj.event === "checkSkuFun") {
        if (formVal.bomList.length > 0) {
          admin.formOpen({
            area: ["90%", "90%"],
            offset: "25px",
            title: "选择sku",
            path: "components/res/benchmarkBook/bookSkuTable.html",
            success: function () {
              parentData.where = {
                inIds: formVal.bomList.map((v) => v.productDetailId).join(",")
              };
            },
            end: function () {
              if (childData.skuObj) {
                let skuObj = childData.skuObj;
                projectTableData[index].semiFinishedId = skuObj.id;
                projectTableData[index].semiFinishedName = skuObj.skuName;
                projectTableData[index].semiFinishedCode = skuObj.skuCode;
                table.reload("productProjectTable", {
                  data: iniList(projectTableData)
                });
              }
            }
          });
        } else {
          layer.msg("当前bom规划里没有物料");
        }
      } else if (obj.event === "deviceFun") {
        if (data.workstationNature == 1) {
          admin.formOpen({
            title: "配置设备机型",
            area: "90%",
            offset: "50px",
            path: "components/device/deviceModel.html",
            success: function () {
              parentData.eventName = "radio";
            },
            end: function () {
              if (childData.list && childData.list.length > 0) {
                let obj = childData.list[0];
                projectTableData[index].deviceType = obj.id;
                projectTableData[index].deviceTypeName = obj.name;
                table.reload("productProjectTable", {
                  data: projectTableData
                });
              }
            }
          });
        } else if (data.workstationNature == 2) {
          admin.formOpen({
            title: "配置工种",
            area: "90%",
            offset: "50px",
            path: "components/product/professionList.html",
            success: function () {
              parentData.eventName = "radio";
            },
            end: function () {
              if (childData.list && childData.list.length > 0) {
                let obj = childData.list[0];
                projectTableData[index].deviceType = obj.id;
                projectTableData[index].deviceTypeName = obj.professionName;
                table.reload("productProjectTable", {
                  data: projectTableData
                });
              }
            }
          });
        } else {
          layer.msg("请选择工位性质");
        }
      } else if (obj.event === "edit") {
        admin.formOpen({
          area: ["90%", "90%"],
          offset: "25px",
          title: "选择sku",
          path: "components/res/benchmarkBook/benchmarkBookByProseForm.html",
          success: function () {
            parentData.data = "edit";
          },
          end: function () {}
        });
      }
      return false;
    });
    function selectProduct(data) {
      let skuSelectModel = admin.formOpen({
        type: 1,
        area: ["1480px", "90%"],
        style: "font-size: 20px;",
        title: "客户产品规划管理",
        // content: $("#skuSelectDiv").html(),
        path: "components/res/benchmarkBook/bookSkuTable.html"
      });
      return skuSelectModel;
    }
    function deleteChildren(parentId) {
      formVal.bomList = formVal.bomList.filter((item) => {
        if (item.parentId === parentId) {
          // 继续递归删除下级节点
          deleteChildren(item.productDetailId);
          return false;
        }
        return true;
      });
    }
    // 监听工具条
    table.on("tool(bomTreeTable)", function (obj) {
      const data = obj.data;
      if (obj.event === "addChild") {
        let skuSelectModel = admin.formOpen({
          type: 1,
          area: ["1480px", "90%"],
          style: "font-size: 20px;",
          title: "客户产品规划管理",
          path: "components/purchase/skuTableForm.html",
          // path: "components/res/benchmarkBook/bookSkuTable.html",
          success: function () {
            // 找到这这一层级上的所有id
            let list = table.cache["#bomTreeTable"];
            let ids = [data.id];
            while (data.parentId !== "-1") {
              let obj = list.find((v) => v.id === data.parentId);
              ids.push(obj.id);
              data.parentId = obj.parentId;
            }
            parentData.notInListIds = ids.join(",");
            console.log(ids);
          },
          end: function () {
            console.log(123, childData);

            if (childData.list && childData.list.length > 0) {
              // let skuObj = { ...childData.skuObj };
              let skuList = childData.list;
              let list = table.cache["#bomTreeTable"];
              skuList = skuList.map((v) => {
                return {
                  id: v.productDetailId,
                  productDetailId: v.productDetailId,
                  productName: v.skuName,
                  productCode: v.skuCode,
                  productSpec: v.skuSpec,
                  productTypeName: v.productTypeName,
                  productAttrName: v.productAttrName,
                  inSkuUnitName: v.mainUnitName,
                  parentId: data.productDetailId
                };
              });
              let parentId = data.productDetailId;
              let grandParentId = [];
              list.push(...skuList);
              table.reload("#bomTreeTable", {
                data: list
              });
              formVal.bomList = list;
              // formVal.bomList.push(...skuList);
              treetableParms.data = formVal.bomList;
              setTimeout(() => {
                treetable.reload(treetableParms);
              }, 400);
            }
          }
        });
      } else if (obj.event === "del") {
        if (data.parentId === "-1") {
          layer.msg("根节点不能删除");
          return;
        }
        console.log("删除", data);

        deleteChildren(data.productDetailId);
        treetableParms.data = formVal.bomList.filter((item) => item.productDetailId !== data.productDetailId);
        console.log(123, treetable);

        treetable.reload(treetableParms);
        formVal.bomList = table.cache["#bomTreeTable"];

        console.log(124, table.cache["#bomTreeTable"]);
      }
    });
    table.on("tool(testItemTable)", function (obj) {
      const data = obj.data;
      let list = table.cache["testItemTable"];
      if (obj.event === "del") {
        const index = $(obj.tr[0]).data("index");
        list.splice(index, 1);
        // formVal.qualityList.splice(index, 1);
        // console.log('formVal.qualityList',formVal.qualityList);

        table.reload("testItemTable", {
          data: [...list]
        });
      } else if (obj.event === "edit") {
        console.log(123);
      }
    });
    table.on("tool(zhijianTable)", function (obj) {
      const data = obj.data;
      if (obj.event === "del") {
        let index = $(obj.tr[0]).data("index");
        let list = table.cache["zhijianTable"];
        list.splice(index, 1);
        table.reload("zhijianTable", { data: list });
      }
    });
    $("#addTestItem").click(function () {
      let productProjectList = table.cache["productProjectTable"];
      if (!productProjectList.some((v) => v.type == 2)) {
        layer.msg("请先添加末工序");
        return;
      }

      let obj = productProjectList.find((v) => v.type == 2);
      if (obj.qualityType != 1) {
        layer.msg("该末工序不需要质检");
        return;
      }
      let list = table.cache["testItemTable"];
      list.push({
        name: "",
        standard: "",
        utensil: "",
        way: "",
        importance: "",
        detectionRate: "",
        productDetailId: formVal.productDetailId,
        skuCode: formVal.skuCode
      });
      table.reload("testItemTable", {
        data: [...list]
      });
      return false;
    });
    $("#moldUploadInfoBtn").click(function () {
      let list = table.cache["productProjectTable"];
      list.push({
        name: "",
        code: "",
        processNumber: "",
        content: "",
        fixture: "",
        measuringTools: "",
        hoursQuota: "",
        salaryQuota: "",
        productDetailId: "",
        qualityType: `0`
      });

      table.reload("productProjectTable", {
        data: iniList([...list])
      });
      return false;
    });
    $("#checkProcess").click(function () {
      admin.formOpen({
        area: ["90%", "90%"],
        title: "选择工序",
        path: "components/product/processInfo.html",
        success: function () {
          parentData.eventName = "checkbox";
          parentData.where = {
            notInListIds: table.cache["productProjectTable"].map((v) => v.id).join(",")
          };
        },
        end: function () {
          if (childData.list && childData.list.length > 0) {
            console.log(123, childData.list);

            let lastIndex = 0;
            if (table.cache["productProjectTable"].length > 0) {
              let lastObj = table.cache["productProjectTable"].at(-1);
              if (lastObj.processNumber) {
                lastIndex = lastObj.processNumber;
              }
            }
            let list = childData.list.map((v, i) => {
              v.name = v.nodeNames;
              v.associationGxId = v.id;
              v.processNumber = Number(lastIndex) + i + 1;
              v.code = table.cache["benchmarkBookFormTable"][0].skuCode + v.processNumber;
              if (v.deviceType) {
                v.workstationNature = 1;
              }
              if (v.productItems) {
                // 筛选不启用的检测项
                v.qualityList = [...v.productItems]
                  .filter((v) => {
                    return !v.isDeleted;
                  })
                  .map((v1) => {
                    v1.way = v1.qualityWayId;
                    v1.utensil = v1.deviceModelSpuId;
                    v1.importance = v1.importanceCode;
                    v1.no = v1.code;
                    return v1;
                  });
              }
              v.qualityType = "0";
              return v;
            });

            let oldList = table.cache["productProjectTable"];

            // formVal.processList.push(processObj);
            // table.reload("productProjectTable", {
            //   data: [...oldList, ...list]
            // });
            setTableCode([...oldList, ...list]);
          }
        }
      });
    });

    form.on("submit(bookSubmit)", function (d) {
      let submitType = $(d.elem).attr("data-type");

      if (!table.cache["benchmarkBookFormTable"][0].bookType) {
        layer.msg("请选择基准书类型");
        return;
      }
      const formData = { ...d.field };

      formData.bookType = table.cache["benchmarkBookFormTable"][0].bookType;
      // formData.type = table.cache["benchmarkBookFormTable"][0].type;
      if (!formData.productDetailId || formData.productDetailId === "") {
        formData.productDetailId = formVal.productDetailId;
      }

      formData.bomList = table.cache["#bomTreeTable"] ? table.cache["#bomTreeTable"] : [];
      formData.echnologyList = table.cache["productProjectTable"];
      let isQuality = formData.echnologyList.every((v) => {
        if (v.skuList) {
          return v.skuList.every((v) => v.quantity);
        } else {
          return true;
        }
      });
      if (!isQuality) {
        layer.msg("请填写关联物料所需数量");
        return;
      }
      let isQualityType = formData.echnologyList.every((v) => {
        if (v.skuList) {
          return v.skuList.every((v) => v.quantity);
        } else {
          return true;
        }
      });
      let isWorkstationNature = formData.echnologyList.find((v) => {
        return v.qualityType == 1 && !v.qualityAttributes;
      });
      if (isWorkstationNature) {
        layer.msg(isWorkstationNature.name + " 未选择质检属性");
        return;
      }
      console.log(12, isWorkstationNature);
      // if (formData.echnologyList.some((v) => !v.semiFinishedId)) {
      //   layer.msg("工艺工序需要选择产成品");
      //   return;
      // }

      if (formData.echnologyList.length == 0) {
        layer.msg("产品工序规划不能为空");
        return;
      }
      formData.qualityList = table.cache["testItemTable"];
      formData.bomList.forEach((v) => {
        // 保留6位小数
        v.inUnitCount = Number(v.inUnitCount).toFixed(6);
        v.count = v.inUnitCount;
      });
      try {
        formData.echnologyList.forEach((v) => {
          v.skuList.forEach((v1) => {
            v1.quantity = Number(v1.quantity).toFixed(6);
          });
        });
      } catch (e) {
        // layui.layer.msg("请填写物料管理中的物料所需数量");
        //  return;
        console.log(e);
      }
      formData.bomList[0].count = 1;

      formData.drawInfos = table.cache["drawImageTable"];
      console.log(formData);

      // return;
      if (nowData.eventName === "add") {
        admin.req(
          "enterprise/benchmarkBook/admin/benchmarkBook/generateBenchmarkBook",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code === 200) {
              if (submitType == "present") {
                layer.msg("暂时保存成功", { icon: 1 });
                formVal.id = res.data;
                nowData.eventName = "edit";
              } else {
                layer.msg(res.msg, { icon: 1 });
                if (nowData.type == "产品规划列表") {
                  layer.closeAll("page");
                  table.reload("#productTaskTableInfo");
                } else if (nowData.type == "基准书列表") {
                  layer.closeAll("page");
                  table.reload("#benchmarkBookInfo");
                } else if (nowData.type == "生产计划列表") {
                  layer.close(nowData.zindex);
                } else {
                  layer.closeAll("page");
                  table.reload("#benchmarkBookInfo");
                }
              }
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          "POST",
          true,
          "application/json; charset=utf-8"
        );
      } else if (nowData.eventName === "edit") {
        formData.id = formVal.id;
        // formData.bomList = formData.bomList.filter((v) => v.parentId != "-1");
        formData.bomList.forEach((v) => {
          v.count = v.inUnitCount;
        });
        admin.req(
          "enterprise/benchmarkBook/admin/benchmarkBook/updateBenchmarkBook",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code === 200) {
              if (submitType == "present") {
                layer.msg("暂时保存成功", { icon: 1 });
              } else {
                layer.msg(res.msg, { icon: 1 });

                if (nowData.type == "产品规划列表") {
                  layer.closeAll("page");
                  table.reload("#productTaskTableInfo");
                } else if (nowData.type == "基准书列表") {
                  layer.closeAll("page");
                  table.reload("#benchmarkBookInfo");
                } else if (nowData.type == "生产计划列表") {
                  layer.close(parentData.zIndex);
                } else {
                  layer.closeAll("page");
                  table.reload("#benchmarkBookInfo");
                }
              }
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          "POST",
          true,
          "application/json; charset=utf-8"
        );
      }
      return false;
    });
  });
</script>
<style>
  #benchmarkBookForm .layui-input-block {
    margin-left: 130px;
  }

  #benchmarkBookForm .layui-form-label {
    width: 100px;
  }

  /* #benchmarkBookFormModel .layui-table-cell {
    overflow: visible !important;
  } */

  /** 自定义字体 **/
  /** 这里使用在线字体，如果需要离线包，请看 font/README.md **/
  @font-face {
    font-family: "soul-icon";
    /* project id 677836 */
    src: url("//at.alicdn.com/t/font_677836_jwq362m0tt.eot");
    src: url("//at.alicdn.com/t/font_677836_jwq362m0tt.eot?#iefix") format("embedded-opentype"), url("//at.alicdn.com/t/font_677836_jwq362m0tt.woff2") format("woff2"),
      url("//at.alicdn.com/t/font_677836_jwq362m0tt.woff") format("woff"), url("//at.alicdn.com/t/font_677836_jwq362m0tt.ttf") format("truetype"),
      url("//at.alicdn.com/t/font_677836_jwq362m0tt.svg#iconfont") format("svg");
  }

  .soul-icon {
    font-family: "soul-icon" !important;
    font-size: 16px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
</style>
